package com.gather.spring.retry.cglib.proxy;


import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author kxd
 * @date 2018/12/5 10:51
 * description:使用spring中MethodInterceptor使用拦截器
 */
public class CglibProxy implements MethodInterceptor {
    /**
     * 拦截器 拦截方法
     *
     * @param o
     * @param method
     * @param objects
     * @param methodProxy
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        int times = 0;
        while (times < RetryConstant.MAX_TIMES) {
            try {
                //调用方法代理invokeSuper
                return methodProxy.invokeSuper(o, objects);
            } catch (Exception e) {
                times++;
                if (times >= RetryConstant.MAX_TIMES) {
                    throw new RuntimeException(e);
                }
            }
        }
        return null;
    }

    public Object getProxy(Class clazz) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        return enhancer.create();
    }
}
